//
//  WCNMulTextEditVC.m
//  WCN
//
//  Created by 杨鑫 on 15/6/1.
//  Copyright (c) 2015年 ShanghaiCize Trade And Business Co., Ltd. All rights reserved.
//

#import "WCNMulTextEditVC.h"

//
#import "UINavigationItem+Offset.h"
#import "NSString+Utilities.h"
#import "UIImage+SQExtension.h"
//


#import "JCAlertView.h"

@interface WCNMulTextEditVC () <UITextViewDelegate>

@property (nonatomic) WCNMulTextEdit type;
@property (weak, nonatomic) IBOutlet UILabel *placeholder;
@property (weak, nonatomic) IBOutlet UITextView *textView;
//@property (weak, nonatomic) IBOutlet UIView *bgview;



@property (weak, nonatomic) IBOutlet UILabel *countLabel;

@end

@implementation WCNMulTextEditVC

- (instancetype)initWithType:(WCNMulTextEdit)type
{
    self = [super init];
    if (self) {
        _type = type;
        _canEmpty = NO;
        _unAbleEdit = NO;
        _textViewEmptyWarm = @"请输入内容";
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageWithColor:kMainColor] forBarMetrics:UIBarMetricsDefault];
    [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor],NSForegroundColorAttributeName,nil]];
    self.navigationController.navigationBar.shadowImage = [[UIImage alloc] init];
    [[UINavigationBar appearance] setTintColor:[UIColor whiteColor]];
    self.navigationController.navigationBar.translucent = NO;
    
    self.view.backgroundColor =HexRGB_WSJ(244, 244, 244);
  
    if (self.textViewPlaceholder) {
        self.placeholder.numberOfLines = 0;
        self.placeholder.text = self.textViewPlaceholder;
    }
    if (self.textViewValue) {
        self.textView.text = self.textViewValue;
        self.textView.backgroundColor = [UIColor whiteColor];
    }

    if (self.unAbleEdit == NO) {

        UIBarButtonItem *sendBtn =[[UIBarButtonItem alloc] initWithTitle:@"完成" style:0 target:self action:@selector(save)];
        
        self.navigationItem.rightBarButtonItem = sendBtn;
        
    }else{
        self.textView.editable = NO;
        
    }
    [self titleView:self.title];
    if (!self.limitCount&& self.limitCount ==0) {
        [self.countLabel removeFromSuperview];
    }else{
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateCountLabel:) name:UITextViewTextDidChangeNotification object:nil];
           self.countLabel.text = [NSString stringWithFormat:@"%d/%ld",0,(long)self.limitCount];
     
//     [self.textView addObserver:self forKeyPath:@"text" options:NSKeyValueObservingOptionNew context:nil];
    }
     
   
    
}
- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.view endEditing:YES];
}
- (void)updateCountLabel:(NSNotification *)not{
    
//    NSInteger count = [text length];
//    self.countLabel.text = [NSString stringWithFormat:@"%d/%d",count,self.limitCount];
    UITextView *textView = not.object;
   
    NSString *lang = [[UITextInputMode currentInputMode] primaryLanguage]; // 键盘输入模式
     NSString *toBeString = textView.text;
    if ([lang isEqualToString:@"zh-Hans"]) { // 简体中文输入，包括简体拼音，健体五笔，简体手写
        UITextRange *selectedRange = [textView markedTextRange];
        //获取高亮部分
        UITextPosition *position = [textView positionFromPosition:selectedRange.start offset:0];
        // 没有高亮选择的字，则对已输入的文字进行字数统计和限制
        if (!position) {
            if (toBeString.length > self.limitCount) {
                textView.text = [toBeString substringToIndex:self.limitCount];
            }
        }
        // 有高亮选择的字符串，则暂不对文字进行统计和限制
        else{
            
        }
    }
    // 中文输入法以外的直接对其统计限制即可，不考虑其他语种情况
    else{
        if (toBeString.length > self.limitCount) {
            textView.text = [toBeString substringToIndex:self.limitCount];
        }  
    }
     self.countLabel.text = [NSString stringWithFormat:@"%d/%d",textView.text.length,self.limitCount];
}



- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.textView becomeFirstResponder];
}
- (void)save
{
    [self.view endEditing:YES];
    NSString *content = self.textView.text;
    if ((!self.canEmpty && [content isEmpty]) || [self isEmpty:content]) {
//        [[WCPopupLayerManager shareMg] showTextOnly:self.textViewEmptyWarm withView:self.view];
        [JCAlertView showOneButtonWithTitle:@"提示" Message:@"输入内容不能为空" ButtonType:JCAlertViewButtonTypeWarn ButtonTitle:@"知道了" Click:^{
            
        }];
        self.textView.text = @"";
        return;
    }
    
    if (self.type == WCNMulTextEditSave) {
        self.callback(content);
        [self.navigationController popViewControllerAnimated:YES];
    } else {

    }
}
 -(void)setUnAbleEdit:(BOOL)unAbleEdit
{
    _unAbleEdit = unAbleEdit;

}
- (void)saveSuccess
{
    if (self.callback) {
        self.callback(nil);
    }
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - Nib Actions

- (IBAction)bgTap:(id)sender {
    [self.view endEditing:YES];
}

#pragma mark - UITextViewDelegate

- (void)textViewDidChange:(UITextView *)textView
{
    NSString *txt = textView.text;
    if (txt.length == 0) {
        textView.backgroundColor = [UIColor clearColor];
    } else {
        textView.backgroundColor = [UIColor whiteColor];
    }
}
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
    NSString *txt = textView.text;
    if (txt.length == 0 && [text isEqualToString:@"\n"]) {
        return NO;
    }
    return YES;
}

//是否为空格
- (BOOL)isEmpty:(NSString *) str {
    
    if (!str) {
        return true;
    } else {
        //A character set containing only the whitespace characters space (U+0020) and tab (U+0009) and the newline and nextline characters (U+000A–U+000D, U+0085).
        NSCharacterSet *set = [NSCharacterSet whitespaceAndNewlineCharacterSet];
        
        //Returns a new string made by removing from both ends of the receiver characters contained in a given character set.
        NSString *trimedString = [str stringByTrimmingCharactersInSet:set];
        
        if ([trimedString length] == 0) {
            return true;
        } else {
            return false;
        }
    }
}



@end
